import { Scope } from "../typings/traverse";
import { parseDirectiveArg, parseDirectiveModifiers, parseDirectiveName } from "../utils/directives";

interface Directive {
    bind: Function;
}
interface Binding {
    name: string;  // 指令名
    path: string;  //  'obj.attr'
    modifiers: Record<string, boolean>;  // 一个包含修饰符的对象
    arg?: string;  //   例子 ：v-vind:attr arg为attr
}

class Directives {
    _directivesMap: Map<string, Directive> = new Map;
    constructor() {
    }
    public addDirective(name: string, directive: Directive) {
        if (!this._directivesMap.has(name)) {
            this._directivesMap.set(name, directive);
        } else {
            throw new Error("不能添加同名指令")
        }
    }
    public getDirective(name: string) {
        return this._directivesMap.get(name);
    }
    public bind(el: PIXI.Container | PIXI.Sprite, element: Element, scope?: Scope) {
        element.getAttributeNames()
            .forEach(_name => {
                let name = parseDirectiveName(_name);
                let path = <string>element.getAttribute(_name);
                let arg: string | undefined = parseDirectiveArg(_name);
                let modifiers = parseDirectiveModifiers(_name);
                if (name) {
                    let binding: Binding = {
                        name,
                        path,
                        arg,
                        modifiers
                    }
                    let directive = this.getDirective(name);
                    if (directive) {
                        directive.bind(el, binding, scope);
                    }
                }
            })
    }
    public update(el: PIXI.Container | PIXI.Sprite, element: Element) {

    }
}

export { Directives }